extends CharacterBody2D


@export var move_speed : float = 50
@export var animator : AnimatedSprite2D

@export var bullet_scene : PackedScene
var is_game_over : bool = false

func _process(delta: float) -> void:
	if velocity == Vector2.ZERO or is_game_over:
		$runningsound.stop()
	elif not $runningsound.playing:
		$runningsound.play()

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _physics_process(delta: float) -> void:
	if not is_game_over:
		velocity = Input.get_vector("move_left", "move_right", "move_up", "move_down") * move_speed
		
		if velocity == Vector2.ZERO:
			animator.play("idle")
		else:
			animator.play("run")

		move_and_slide()

func game_over():
	if not is_game_over:
		is_game_over = true
		animator.play("die")
		$gameoversound.play()
		get_tree().current_scene.show_game_over()
		await get_tree().create_timer(3).timeout
		get_tree().reload_current_scene()


func _on_timer_timeout() -> void:
	if velocity != Vector2.ZERO or is_game_over:
		return
	
	$firesound.play()
	
	var bullet = bullet_scene.instantiate()
	bullet.position = position + Vector2(6, 6)
	get_tree().current_scene.add_child(bullet)
